package com.csu.hemiao.controller;

import com.csu.hemiao.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.util.Random;

@Controller
@RequestMapping(method = RequestMethod.GET, produces = "image/png")
public class VerificationController {

    @Autowired
    RedisService redisService;

    @GetMapping("/verification")
    public String verification(HttpServletRequest req, HttpServletResponse resp)throws IOException {
        int[] rightValidCode={0,0,0,0};

        resp.setContentType("image/jpeg");//jpeg是图片格式。设置响应内容的类型为jpeg的图片
        int width=64;
        int height=40;
        BufferedImage bImg=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g=bImg.getGraphics();

        //背景
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        //字体颜色
        g.setFont(new Font("aa", Font.BOLD,18));
        //用随机数生成验证码:4个0~9以内的整数
        Random r=new Random();
        for(int i=0;i<4;i++){
            int t=r.nextInt(10);//10以内的随机整数
            rightValidCode[i] = t;
            int y=10+r.nextInt(20);//上下位置:10~30
            Color c=new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawString(""+t, i*16, y);
        }
        //画干扰线
        for(int i=1;i<8;i++){
            Color c=new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }

        redisService.set("rightValidCode",rightValidCode);

        //把图形刷到bImg对象中
        g.dispose();//相当于IO中的close()方法带自动flush();
        ImageIO.write(bImg,"JPEG", resp.getOutputStream());//通过resp获取req的outputStream对象,发向客户端的socket的封装,即写到客户端

        return null;
    }
}
